﻿using Sasa.QualityTools.CodeAnalysis.Common;
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Models
{
    public class CodeAnalysis
    {
        public string FxCopCmdPath { get; set; }

        public string FxCopCmdOption { get; set; }

        public FxCopReport Report { get; private set; }


        public void Perform()
        {
            var process = new Process();
            process.StartInfo = new ProcessStartInfo(FxCopCmdPath, FxCopCmdOption);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = false;
            process.StartInfo.RedirectStandardError = false;

            Logger.Info("Performing code analysis (command = {0} {1}).", FxCopCmdPath, FxCopCmdOption);

            process.Start();
            process.WaitForExit();
            if (process.ExitCode != 0 && process.ExitCode != 1024)
            {
                var message = "Failed to analyze code because FxCopCmd returned error code '" + process.ExitCode + "'.";
                Logger.Error(message);
                throw new CodeAnalysisException(message);
            }

            var match = Regex.Match(FxCopCmdOption, @"/o:""(.+?)""");
            var path = match.Groups[1].Value;
            Report = FxCopReport.Load(path);
        }
    }
}
